package com.gy.File;

import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
public class FileUtils {

    /**
     * 检查文件是否为支持的格式
     *
     * @param fileName 文件名
     * @return 是否支持
     */
    public static boolean isSupportedFileType(String fileName) {
        String extension = getExtension(fileName).toLowerCase();
        return extension.equals("pdf") || extension.equals("jpg") || extension.equals("jpeg") || extension.equals("png");
    }

    /**
     * 获取文件扩展名
     *
     * @param fileName 文件名
     * @return 扩展名
     */
    public static String getExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "";
        }
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex == -1) {
            return ""; // 文件名中没有点，返回空字符串
        }
        return fileName.substring(lastDotIndex + 1);
    }

    /**
     * 检查文件是否为图像文件
     *
     * @param fileName 文件名
     * @return 是否为图像文件
     */
    public static boolean isImageFile(String fileName) {
        String lowerFileName = fileName.toLowerCase();
        return lowerFileName.endsWith(".jpg") || lowerFileName.endsWith(".jpeg") ||
                lowerFileName.endsWith(".png") || lowerFileName.endsWith(".gif");
    }


    /**
     * 将图片转换为 PDF 格式
     *
     * @param imageFile 图片文件
     * @return 转换后的 MultipartFile 格式 PDF 文件
     * @throws IOException 转换过程中出现的异常
     */
    public static MultipartFile convertImageToPdf(MultipartFile imageFile) throws IOException {
        try (InputStream inputStream = imageFile.getInputStream()) {
            // 读取图片
            BufferedImage image = ImageIO.read(inputStream);

            // 创建 PDF 文档
            PDDocument document = new PDDocument();
            PDPage page = new PDPage(new PDRectangle(image.getWidth(), image.getHeight()));
            document.addPage(page);

            // 将图片数据转换为 PDImageXObject
            PDImageXObject pdImage = PDImageXObject.createFromByteArray(document, imageFile.getBytes(), imageFile.getOriginalFilename());

            // 将图片绘制到 PDF 页面上
            try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
                contentStream.drawImage(pdImage, 0, 0);
            }

            // 保存 PDF 文件到字节输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            document.save(baos);
            document.close();

            // 将字节数组转换为 MultipartFile
            return new InMemoryMultipartFile(
                    imageFile.getName(),
                    imageFile.getOriginalFilename().replaceFirst("[.][^.]+$", ".pdf"),
                    "application/pdf",
                    baos.toByteArray()
            );
        }
    }

    // 新增方法：将图片字节数组转换为 PDF 字节数组
    public static byte[] convertImageToPdfBytes(byte[] imageBytes, String fileName) throws IOException {
        try (ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes)) {
            BufferedImage image = ImageIO.read(bais);

            PDDocument document = new PDDocument();
            PDPage page = new PDPage(new PDRectangle(image.getWidth(), image.getHeight()));
            document.addPage(page);

            PDImageXObject pdImage = PDImageXObject.createFromByteArray(document, imageBytes, fileName);

            try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
                contentStream.drawImage(pdImage, 0, 0);
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            document.save(baos);
            document.close();

            return baos.toByteArray();
        }
    }

    public static boolean isPdfFile(String originalFileName) {
        String extension = getExtension(originalFileName).toLowerCase();
        return extension.equals("pdf");
    }



    // 内存中的 MultipartFile 实现
    private static class InMemoryMultipartFile implements MultipartFile {
        private final String name;
        private final String originalFilename;
        private final String contentType;
        private final byte[] content;

        public InMemoryMultipartFile(String name, String originalFilename, String contentType, byte[] content) {
            this.name = name;
            this.originalFilename = originalFilename;
            this.contentType = contentType;
            this.content = content;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public String getOriginalFilename() {
            return originalFilename;
        }

        @Override
        public String getContentType() {
            return contentType;
        }

        @Override
        public boolean isEmpty() {
            return content == null || content.length == 0;
        }

        @Override
        public long getSize() {
            return content.length;
        }

        @Override
        public byte[] getBytes() {
            return content;
        }

        @Override
        public InputStream getInputStream() {
            return new ByteArrayInputStream(content);
        }

        @Override
        public void transferTo(java.io.File dest) throws IOException, IllegalStateException {
            throw new UnsupportedOperationException("Not implemented");
        }

    }
}
